package Download;

import util.DownloadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 完成图片下载功能，点击连接后跳出下载提示框
 * 步骤：
 *      1.获取文件名称
 *      2.使用字节输入流加载文件进内存
 *      3.指定resp的响应头：content-disposition:attachment; filename=xxx
 *      4.将数据写出到resp的输出流
 */
@WebServlet("/DownloadServlet")
public class DownloadServletDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数，文件名称
        String filename = req.getParameter("filename");

        //1.使用字节输入流加载文件进内存
        //1.1找到服务器的路径
        ServletContext context = this.getServletContext();
        String path = context.getRealPath("/img/" + filename);

        //1.2使用字节流关联
        FileInputStream fis = new FileInputStream(path);

        //2.设置resp的响应头
        //2.1 content-type
        String type = context.getMimeType(filename);
        resp.setHeader("content-type",type);


        //解决中文文件名乱码问题
        String agent = req.getHeader("user-agent");

        filename = DownloadUtils.getFileName(agent,filename);

        //2.2 content-disposition
        resp.setHeader("content-disposition","attachment;filename="+filename);

        //3.将输入流的数据写到输出流
        ServletOutputStream ops = resp.getOutputStream();
        byte[] buff =new byte[1024*8];
        int len = 0;
        while ((len=fis.read(buff))!=-1){
            ops.write(buff,0,len);
        }
        fis.close();
    }
}
